"""
下载对话框处理器

专门处理下载对话框的检测和操作
"""

import asyncio
import sys
from typing import Dict, Any, Optional, List
from playwright.async_api import Page
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

try:
    from src.browser.page_handler import BasePageHandler
    from src.utils.logger import get_logger
except ImportError:
    try:
        from ..page_handler import BasePageHandler
        from utils.logger import get_logger
    except ImportError:
        from browser.page_handler import BasePageHandler
        from utils.logger import get_logger

logger = get_logger(__name__)


class DownloadDialogHandler(BasePageHandler):
    """下载对话框处理器类"""
    
    def __init__(self, page: Page):
        super().__init__(page)
        self.dialog_selectors = [
            # SweetAlert2 对话框选择器（优先级最高）
            'div.swal2-container.swal2-center.swal2-fade.swal2-shown',
            '.swal2-container.swal2-shown',
            '.swal2-popup',
            
            # 下载对话框选择器
            '.download-dialog',
            '.download-modal',
            '.save-dialog',
            '.file-dialog',
            
            # 通用对话框选择器
            '.modal:has-text("下载")',
            '.popup:has-text("下载")',
            '.dialog:has-text("下载")',
            'dialog[open]:has-text("下载")',
            
            # 浏览器原生下载对话框
            '[role="dialog"]:has-text("下载")',
            '[role="dialog"]:has-text("保存")',
            '[role="dialog"]:has-text("另存为")',
            
            # 特定网站的下载对话框
            '.download-popup',
            '.save-popup',
            '.file-save-dialog',
            '#download-dialog',
            '#save-dialog'
        ]
        
        self.action_selectors = {
            'save': [
                # SweetAlert2 确认按钮（优先级最高）
                'button.swal2-confirm.swal2-styled',
                'div.swal2-actions > button.swal2-confirm.swal2-styled',
                'body > div.swal2-container.swal2-center.swal2-fade.swal2-shown > div > div.swal2-actions > button.swal2-confirm.swal2-styled',
                
                # 通用保存按钮
                'button:has-text("保存")',
                'button:has-text("下载")',
                'button:has-text("立即下载")',
                'button:has-text("确定")',
                'button:has-text("OK")',
                '.save-btn',
                '.download-btn',
                '#save-button',
                '#download-button'
            ],
            'cancel': [
                # SweetAlert2 取消按钮
                'button.swal2-cancel.swal2-styled',
                'div.swal2-actions > button.swal2-cancel.swal2-styled',
                
                # 通用取消按钮
                'button:has-text("取消")',
                'button:has-text("关闭")',
                'button:has-text("Cancel")',
                '.cancel-btn',
                '.close-btn',
                '#cancel-button'
            ],
            'browse': [
                'button:has-text("浏览")',
                'button:has-text("选择文件夹")',
                'button:has-text("Browse")',
                '.browse-btn',
                '.folder-btn'
            ]
        }
    
    async def handle(self) -> Dict[str, Any]:
        """
        处理下载对话框
        
        Returns:
            Dict: 处理结果
        """
        try:
            # 检测下载对话框
            dialog_info = await self.detect_download_dialog()
            
            if not dialog_info:
                return {
                    'dialog_detected': False,
                    'message': '未检测到下载对话框'
                }
            
            # 分析对话框内容
            dialog_analysis = await self.analyze_dialog(dialog_info)
            
            # 执行默认操作（通常是保存）
            action_result = await self.perform_default_action(dialog_info)
            
            result = {
                'dialog_detected': True,
                'dialog_info': dialog_info,
                'dialog_analysis': dialog_analysis,
                'action_result': action_result,
                'success': action_result.get('success', False)
            }
            
            self.logger.info(f"下载对话框处理完成: {result['success']}")
            return result
            
        except Exception as e:
            self.logger.error(f"下载对话框处理失败: {str(e)}")
            return {'error': str(e), 'dialog_detected': False}
    
    async def detect_download_dialog(self) -> Optional[Dict[str, Any]]:
        """
        检测下载对话框
        
        Returns:
            Dict: 对话框信息
        """
        try:
            # 首先检测SweetAlert2对话框
            swal2_dialog = await self._detect_swal2_dialog()
            if swal2_dialog:
                return swal2_dialog
            
            # 然后检测其他类型的对话框
            for selector in self.dialog_selectors:
                try:
                    element = await self.page.query_selector(selector)
                    if element and await element.is_visible():
                        dialog_info = await self._get_dialog_info(element, selector)
                        if dialog_info:
                            self.logger.info(f"检测到下载对话框: {selector}")
                            return dialog_info
                except Exception as e:
                    self.logger.debug(f"检查对话框选择器 {selector} 失败: {str(e)}")
            
            # 如果没有找到，尝试智能检测
            return await self._smart_detect_dialog()
            
        except Exception as e:
            self.logger.error(f"检测下载对话框失败: {str(e)}")
            return None

    async def _detect_swal2_dialog(self) -> Optional[Dict[str, Any]]:
        """
        专门检测SweetAlert2对话框
        
        Returns:
            Dict: SweetAlert2对话框信息
        """
        try:
            # 检测SweetAlert2容器
            swal2_selectors = [
                'div.swal2-container.swal2-center.swal2-fade.swal2-shown',
                '.swal2-container.swal2-shown',
                '.swal2-popup'
            ]
            
            for selector in swal2_selectors:
                element = await self.page.query_selector(selector)
                if element and await element.is_visible():
                    # 等待SweetAlert2动画完成
                    await asyncio.sleep(0.8)
                    
                    # 再次检查元素是否仍然可见和稳定
                    try:
                        await self.page.wait_for_function(
                            """(element) => {
                                const rect = element.getBoundingClientRect();
                                return rect.width > 0 && rect.height > 0 && 
                                       window.getComputedStyle(element).visibility !== 'hidden' &&
                                       window.getComputedStyle(element).opacity !== '0';
                            }""",
                            element,
                            timeout=3000
                        )
                    except Exception:
                        # 如果等待失败，继续尝试下一个选择器
                        continue
                    
                    # 检查是否包含下载相关内容
                    text_content = await element.text_content()
                    if text_content and any(keyword in text_content.lower() 
                                          for keyword in ['下载', 'download', '立即下载']):
                        
                        # 获取SweetAlert2对话框信息
                        dialog_info = await self._get_swal2_dialog_info(element, selector)
                        if dialog_info:
                            self.logger.info(f"检测到SweetAlert2下载对话框: {selector}")
                            return dialog_info
            
            return None
            
        except Exception as e:
            self.logger.debug(f"检测SweetAlert2对话框失败: {str(e)}")
            return None

    async def _get_swal2_dialog_info(self, element, selector: str) -> Optional[Dict[str, Any]]:
        """
        获取SweetAlert2对话框信息
        
        Args:
            element: 对话框元素
            selector: 选择器
            
        Returns:
            Dict: 对话框信息
        """
        try:
            # 获取对话框基本信息
            text_content = await element.text_content()
            bounding_box = await element.bounding_box()
            
            # 查找SweetAlert2特定的按钮
            swal2_buttons = await self._find_swal2_buttons(element)
            
            # 查找标题和内容
            title_element = await element.query_selector('.swal2-title')
            content_element = await element.query_selector('.swal2-content, .swal2-html-container')
            
            title_text = await title_element.text_content() if title_element else ''
            content_text = await content_element.text_content() if content_element else ''
            
            dialog_info = {
                'element': element,
                'selector': selector,
                'text_content': text_content,
                'title': title_text,
                'content': content_text,
                'position': bounding_box,
                'action_buttons': swal2_buttons,
                'input_fields': [],  # SweetAlert2通常不包含输入框
                'dialog_type': 'swal2_download_dialog',
                'is_swal2': True
            }
            
            return dialog_info
            
        except Exception as e:
            self.logger.debug(f"获取SweetAlert2对话框信息失败: {str(e)}")
            return None

    async def _find_swal2_buttons(self, dialog_element) -> Dict[str, List[Dict[str, Any]]]:
        """
        查找SweetAlert2对话框中的按钮
        
        Args:
            dialog_element: 对话框元素
            
        Returns:
            Dict: 按钮分类信息
        """
        buttons = {'save': [], 'cancel': [], 'browse': [], 'other': []}
        
        try:
            # 查找SweetAlert2特定的按钮
            confirm_buttons = await dialog_element.query_selector_all('button.swal2-confirm')
            cancel_buttons = await dialog_element.query_selector_all('button.swal2-cancel')
            deny_buttons = await dialog_element.query_selector_all('button.swal2-deny')
            
            # 处理确认按钮
            for button in confirm_buttons:
                if await button.is_visible():
                    button_info = {
                        'element': button,
                        'text': await button.text_content(),
                        'type': 'button',
                        'class': await button.get_attribute('class'),
                        'id': await button.get_attribute('id'),
                        'swal2_type': 'confirm'
                    }
                    buttons['save'].append(button_info)
            
            # 处理取消按钮
            for button in cancel_buttons:
                if await button.is_visible():
                    button_info = {
                        'element': button,
                        'text': await button.text_content(),
                        'type': 'button',
                        'class': await button.get_attribute('class'),
                        'id': await button.get_attribute('id'),
                        'swal2_type': 'cancel'
                    }
                    buttons['cancel'].append(button_info)
            
            # 处理拒绝按钮
            for button in deny_buttons:
                if await button.is_visible():
                    button_info = {
                        'element': button,
                        'text': await button.text_content(),
                        'type': 'button',
                        'class': await button.get_attribute('class'),
                        'id': await button.get_attribute('id'),
                        'swal2_type': 'deny'
                    }
                    buttons['cancel'].append(button_info)
            
            return buttons
            
        except Exception as e:
            self.logger.debug(f"查找SweetAlert2按钮失败: {str(e)}")
            return buttons
    
    async def _get_dialog_info(self, element, selector: str) -> Optional[Dict[str, Any]]:
        """
        获取对话框信息
        
        Args:
            element: 对话框元素
            selector: 选择器
            
        Returns:
            Dict: 对话框信息
        """
        try:
            # 获取对话框基本信息
            text_content = await element.text_content()
            bounding_box = await element.bounding_box()
            
            # 查找操作按钮
            action_buttons = await self._find_action_buttons(element)
            
            # 查找输入框（文件名、路径等）
            input_fields = await self._find_input_fields(element)
            
            dialog_info = {
                'element': element,
                'selector': selector,
                'text_content': text_content,
                'position': bounding_box,
                'action_buttons': action_buttons,
                'input_fields': input_fields,
                'dialog_type': await self._determine_dialog_type(text_content, action_buttons)
            }
            
            return dialog_info
            
        except Exception as e:
            self.logger.debug(f"获取对话框信息失败: {str(e)}")
            return None
    
    async def _find_action_buttons(self, dialog_element) -> Dict[str, List[Dict[str, Any]]]:
        """
        查找对话框中的操作按钮
        
        Args:
            dialog_element: 对话框元素
            
        Returns:
            Dict: 按钮分类信息
        """
        buttons = {'save': [], 'cancel': [], 'browse': [], 'other': []}
        
        try:
            # 查找所有按钮
            all_buttons = await dialog_element.query_selector_all('button, input[type="button"], input[type="submit"]')
            
            for button in all_buttons:
                if not await button.is_visible():
                    continue
                
                button_info = {
                    'element': button,
                    'text': await button.text_content(),
                    'type': await button.get_attribute('type'),
                    'class': await button.get_attribute('class'),
                    'id': await button.get_attribute('id')
                }
                
                # 分类按钮
                button_text = button_info['text'].lower() if button_info['text'] else ''
                button_class = button_info['class'].lower() if button_info['class'] else ''
                
                categorized = False
                for action_type, selectors in self.action_selectors.items():
                    for selector in selectors:
                        if ':has-text(' in selector:
                            # 提取文本匹配
                            text_match = selector.split(':has-text("')[1].split('")')[0].lower()
                            if text_match in button_text:
                                buttons[action_type].append(button_info)
                                categorized = True
                                break
                        elif selector.startswith('.') and selector[1:] in button_class:
                            buttons[action_type].append(button_info)
                            categorized = True
                            break
                        elif selector.startswith('#') and selector[1:] == button_info['id']:
                            buttons[action_type].append(button_info)
                            categorized = True
                            break
                    
                    if categorized:
                        break
                
                if not categorized:
                    buttons['other'].append(button_info)
            
            return buttons
            
        except Exception as e:
            self.logger.debug(f"查找操作按钮失败: {str(e)}")
            return buttons
    
    async def _find_input_fields(self, dialog_element) -> List[Dict[str, Any]]:
        """
        查找对话框中的输入框
        
        Args:
            dialog_element: 对话框元素
            
        Returns:
            List: 输入框信息列表
        """
        input_fields = []
        
        try:
            inputs = await dialog_element.query_selector_all('input[type="text"], input[type="file"], input:not([type]), select, textarea')
            
            for input_elem in inputs:
                if not await input_elem.is_visible():
                    continue
                
                input_info = {
                    'element': input_elem,
                    'type': await input_elem.get_attribute('type'),
                    'name': await input_elem.get_attribute('name'),
                    'placeholder': await input_elem.get_attribute('placeholder'),
                    'value': await input_elem.get_attribute('value'),
                    'class': await input_elem.get_attribute('class'),
                    'id': await input_elem.get_attribute('id')
                }
                
                input_fields.append(input_info)
            
            return input_fields
            
        except Exception as e:
            self.logger.debug(f"查找输入框失败: {str(e)}")
            return []
    
    async def _determine_dialog_type(self, text_content: str, action_buttons: Dict) -> str:
        """
        确定对话框类型
        
        Args:
            text_content: 对话框文本内容
            action_buttons: 操作按钮信息
            
        Returns:
            str: 对话框类型
        """
        try:
            text_lower = text_content.lower() if text_content else ''
            
            # 检查关键词
            if any(keyword in text_lower for keyword in ['另存为', 'save as', '保存文件']):
                return 'save_as_dialog'
            elif any(keyword in text_lower for keyword in ['下载', 'download']):
                return 'download_dialog'
            elif any(keyword in text_lower for keyword in ['选择文件夹', 'choose folder', 'select folder']):
                return 'folder_dialog'
            elif len(action_buttons['save']) > 0:
                return 'save_dialog'
            else:
                return 'unknown_dialog'
                
        except Exception as e:
            self.logger.debug(f"确定对话框类型失败: {str(e)}")
            return 'unknown_dialog'
    
    async def _smart_detect_dialog(self) -> Optional[Dict[str, Any]]:
        """
        智能检测对话框
        
        Returns:
            Dict: 对话框信息
        """
        try:
            # 查找所有可能的对话框元素
            potential_dialogs = await self.page.query_selector_all(
                'dialog, .modal, .popup, .dialog, [role="dialog"], [role="alertdialog"]'
            )
            
            for dialog in potential_dialogs:
                if not await dialog.is_visible():
                    continue
                
                text_content = await dialog.text_content()
                if not text_content:
                    continue
                
                text_lower = text_content.lower()
                
                # 检查是否包含下载相关关键词
                download_keywords = ['下载', 'download', '保存', 'save', '另存为', 'save as']
                if any(keyword in text_lower for keyword in download_keywords):
                    dialog_info = await self._get_dialog_info(dialog, 'smart_detection')
                    if dialog_info:
                        self.logger.info("智能检测到下载对话框")
                        return dialog_info
            
            return None
            
        except Exception as e:
            self.logger.error(f"智能检测对话框失败: {str(e)}")
            return None
    
    async def analyze_dialog(self, dialog_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        分析对话框内容
        
        Args:
            dialog_info: 对话框信息
            
        Returns:
            Dict: 分析结果
        """
        try:
            analysis = {
                'dialog_type': dialog_info['dialog_type'],
                'has_save_button': len(dialog_info['action_buttons']['save']) > 0,
                'has_cancel_button': len(dialog_info['action_buttons']['cancel']) > 0,
                'has_browse_button': len(dialog_info['action_buttons']['browse']) > 0,
                'has_input_fields': len(dialog_info['input_fields']) > 0,
                'recommended_action': 'save',  # 默认推荐保存
                'file_name_field': None,
                'folder_path_field': None
            }
            
            # 分析输入框
            for input_field in dialog_info['input_fields']:
                input_name = input_field.get('name', '').lower()
                input_placeholder = input_field.get('placeholder', '').lower()
                input_class = input_field.get('class', '').lower()
                
                if any(keyword in f"{input_name} {input_placeholder} {input_class}" 
                       for keyword in ['filename', 'name', '文件名']):
                    analysis['file_name_field'] = input_field
                elif any(keyword in f"{input_name} {input_placeholder} {input_class}" 
                         for keyword in ['folder', 'path', '路径', '文件夹']):
                    analysis['folder_path_field'] = input_field
            
            # 确定推荐操作
            if analysis['has_save_button']:
                analysis['recommended_action'] = 'save'
            elif analysis['has_cancel_button']:
                analysis['recommended_action'] = 'cancel'
            else:
                analysis['recommended_action'] = 'close'
            
            return analysis
            
        except Exception as e:
            self.logger.error(f"分析对话框失败: {str(e)}")
            return {'error': str(e)}
    
    async def perform_default_action(self, dialog_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行默认操作（通常是保存）
        
        Args:
            dialog_info: 对话框信息
            
        Returns:
            Dict: 操作结果
        """
        try:
            action_buttons = dialog_info['action_buttons']
            
            # 检查是否是SweetAlert2对话框
            is_swal2 = dialog_info.get('is_swal2', False)
            
            # 优先尝试保存按钮
            if action_buttons['save']:
                button_info = action_buttons['save'][0]
                
                if is_swal2:
                    # 对于SweetAlert2对话框，使用更稳健的点击策略
                    result = await self._click_swal2_button(button_info, dialog_info)
                else:
                    # 对于普通对话框，使用标准点击
                    result = await self._click_standard_button(button_info, dialog_info)
                
                if result['success']:
                    return result
                
                # 如果第一次点击失败，尝试备用策略
                self.logger.warning("第一次点击失败，尝试备用策略")
                return await self._try_alternative_click_strategies(dialog_info)
            
            # 如果没有保存按钮，尝试确定按钮
            elif action_buttons['other']:
                for button_info in action_buttons['other']:
                    button_text = button_info['text'].lower()
                    if any(keyword in button_text for keyword in ['确定', 'ok', '是', 'yes']):
                        if is_swal2:
                            result = await self._click_swal2_button(button_info, dialog_info)
                        else:
                            result = await self._click_standard_button(button_info, dialog_info)
                        
                        if result['success']:
                            return result
            
            # 如果都没有，尝试备用策略
            return await self._try_alternative_click_strategies(dialog_info)
            
        except Exception as e:
            self.logger.error(f"执行默认操作失败: {str(e)}")
            return {'success': False, 'error': str(e)}

    async def _click_swal2_button(self, button_info: Dict[str, Any], dialog_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        点击SweetAlert2按钮的稳健策略
        
        Args:
            button_info: 按钮信息
            dialog_info: 对话框信息
            
        Returns:
            Dict: 点击结果
        """
        try:
            button_element = button_info['element']
            button_text = button_info.get('text', '')
            
            # 等待对话框动画完成
            await asyncio.sleep(0.5)
            
            # 确保按钮可见且稳定
            await self.page.wait_for_function(
                """(button) => {
                    const rect = button.getBoundingClientRect();
                    return rect.width > 0 && rect.height > 0 && 
                           window.getComputedStyle(button).visibility !== 'hidden' &&
                           !button.disabled;
                }""",
                button_element,
                timeout=5000
            )
            
            # 尝试多种点击方式
            click_methods = [
                # 方法1: 标准点击
                lambda: button_element.click(),
                # 方法2: 强制点击
                lambda: button_element.click(force=True),
                # 方法3: 通过JavaScript点击
                lambda: self.page.evaluate("(button) => button.click()", button_element),
                # 方法4: 通过坐标点击
                lambda: self._click_by_coordinates(button_element)
            ]
            
            for i, click_method in enumerate(click_methods):
                try:
                    self.logger.info(f"尝试点击方法 {i+1}: {button_text}")
                    await click_method()
                    
                    # 等待一段时间检查是否成功
                    await asyncio.sleep(1)
                    
                    # 检查对话框是否已关闭
                    try:
                        is_closed = not await dialog_info['element'].is_visible()
                        if is_closed:
                            self.logger.info(f"SweetAlert2按钮点击成功 (方法 {i+1}): {button_text}")
                            return {
                                'success': True,
                                'action': 'save',
                                'method': f'swal2_click_method_{i+1}',
                                'message': f'点击{button_text}按钮成功'
                            }
                    except Exception:
                        # 如果检查失败，继续尝试下一种方法
                        pass
                        
                except Exception as e:
                    self.logger.debug(f"点击方法 {i+1} 失败: {str(e)}")
                    continue
            
            return {
                'success': False,
                'action': 'save',
                'error': 'All click methods failed',
                'message': f'所有点击方法都失败了: {button_text}'
            }
            
        except Exception as e:
            self.logger.error(f"SweetAlert2按钮点击失败: {str(e)}")
            return {'success': False, 'error': str(e)}

    async def _click_standard_button(self, button_info: Dict[str, Any], dialog_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        点击标准按钮
        
        Args:
            button_info: 按钮信息
            dialog_info: 对话框信息
            
        Returns:
            Dict: 点击结果
        """
        try:
            button_element = button_info['element']
            button_text = button_info.get('text', '')
            
            await button_element.click()
            self.logger.info(f"点击标准按钮: {button_text}")
            
            # 等待对话框消失
            await asyncio.sleep(1)
            
            # 检查对话框是否已关闭
            is_closed = not await dialog_info['element'].is_visible()
            
            return {
                'success': is_closed,
                'action': 'save',
                'message': f'点击{button_text}按钮' + ('成功' if is_closed else '失败')
            }
            
        except Exception as e:
            self.logger.error(f"标准按钮点击失败: {str(e)}")
            return {'success': False, 'error': str(e)}

    async def _click_by_coordinates(self, element) -> None:
        """
        通过坐标点击元素
        
        Args:
            element: 要点击的元素
        """
        bounding_box = await element.bounding_box()
        if bounding_box:
            x = bounding_box['x'] + bounding_box['width'] / 2
            y = bounding_box['y'] + bounding_box['height'] / 2
            await self.page.mouse.click(x, y)

    async def _try_alternative_click_strategies(self, dialog_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        尝试备用点击策略
        
        Args:
            dialog_info: 对话框信息
            
        Returns:
            Dict: 操作结果
        """
        try:
            # 策略1: 尝试按ESC键
            try:
                await self.page.keyboard.press('Escape')
                self.logger.info("尝试按ESC键关闭对话框")
                await asyncio.sleep(1)
                
                is_closed = not await dialog_info['element'].is_visible()
                if is_closed:
                    return {
                        'success': True,
                        'action': 'escape',
                        'message': '按ESC键成功关闭对话框'
                    }
            except Exception as e:
                self.logger.debug(f"ESC键策略失败: {str(e)}")
            
            # 策略2: 尝试按Enter键
            try:
                await self.page.keyboard.press('Enter')
                self.logger.info("尝试按Enter键确认对话框")
                await asyncio.sleep(1)
                
                is_closed = not await dialog_info['element'].is_visible()
                if is_closed:
                    return {
                        'success': True,
                        'action': 'enter',
                        'message': '按Enter键成功确认对话框'
                    }
            except Exception as e:
                self.logger.debug(f"Enter键策略失败: {str(e)}")
            
            # 策略3: 尝试点击对话框外部区域
            try:
                await self.page.mouse.click(10, 10)  # 点击左上角
                self.logger.info("尝试点击对话框外部区域")
                await asyncio.sleep(1)
                
                is_closed = not await dialog_info['element'].is_visible()
                if is_closed:
                    return {
                        'success': True,
                        'action': 'click_outside',
                        'message': '点击外部区域成功关闭对话框'
                    }
            except Exception as e:
                self.logger.debug(f"点击外部区域策略失败: {str(e)}")
            
            return {
                'success': False,
                'action': 'none',
                'message': '所有备用策略都失败了'
            }
            
        except Exception as e:
            self.logger.error(f"备用策略执行失败: {str(e)}")
            return {'success': False, 'error': str(e)}
    
    async def set_download_path(self, dialog_info: Dict[str, Any], path: str) -> Dict[str, Any]:
        """
        设置下载路径
        
        Args:
            dialog_info: 对话框信息
            path: 下载路径
            
        Returns:
            Dict: 设置结果
        """
        try:
            # 查找路径输入框
            path_field = None
            for input_field in dialog_info['input_fields']:
                input_name = input_field.get('name', '').lower()
                input_placeholder = input_field.get('placeholder', '').lower()
                
                if any(keyword in f"{input_name} {input_placeholder}" 
                       for keyword in ['path', 'folder', '路径', '文件夹']):
                    path_field = input_field
                    break
            
            if not path_field:
                return {'success': False, 'error': '未找到路径输入框'}
            
            # 清空并输入新路径
            path_element = path_field['element']
            await path_element.click()
            await path_element.fill('')
            await path_element.type(path)
            
            self.logger.info(f"设置下载路径: {path}")
            
            return {'success': True, 'path': path}
            
        except Exception as e:
            self.logger.error(f"设置下载路径失败: {str(e)}")
            return {'success': False, 'error': str(e)}
    
    async def set_file_name(self, dialog_info: Dict[str, Any], filename: str) -> Dict[str, Any]:
        """
        设置文件名
        
        Args:
            dialog_info: 对话框信息
            filename: 文件名
            
        Returns:
            Dict: 设置结果
        """
        try:
            # 查找文件名输入框
            name_field = None
            for input_field in dialog_info['input_fields']:
                input_name = input_field.get('name', '').lower()
                input_placeholder = input_field.get('placeholder', '').lower()
                
                if any(keyword in f"{input_name} {input_placeholder}" 
                       for keyword in ['filename', 'name', '文件名']):
                    name_field = input_field
                    break
            
            if not name_field:
                return {'success': False, 'error': '未找到文件名输入框'}
            
            # 清空并输入新文件名
            name_element = name_field['element']
            await name_element.click()
            await name_element.fill('')
            await name_element.type(filename)
            
            self.logger.info(f"设置文件名: {filename}")
            
            return {'success': True, 'filename': filename}
            
        except Exception as e:
            self.logger.error(f"设置文件名失败: {str(e)}")
            return {'success': False, 'error': str(e)}